using System;
using System.Linq;
using System.Windows.Forms;
using WorkOrderPrinter.Models;
using WorkOrderPrinter.Services;

namespace WorkOrderPrinter
{
    public partial class MainForm : Form
    {

        private PrintTemplate _currentTemplate;
        private ITemplateService _templateService;

        public MainForm()
        {
            InitializeComponent();
            // 初始化日期为今天
            dtpDate.Value = DateTime.Now;
            // 初始化起始序号
            serialNumber.Value = 1;
            // 初始化模板服务
            _templateService = new TemplateService();
            //初始化打印模板
            InitializePrintTemplate();
        }

        private void InitializePrintTemplate()
        {
            LoadTemplateList();
            UpdateCurrentTemplate();
        }

        private void LoadTemplateList()
        {
            var templates = _templateService.GetAllTemplates();
            cboTemplates.DataSource = null;
            cboTemplates.DisplayMember = "Name";
            cboTemplates.ValueMember = "Id";
            cboTemplates.DataSource = templates;
        }

        private WorkOrder GetWorkOrderFromForm()
        {
            return new WorkOrder
            {
                Model = txtModel.Text.Trim(),
                Batch = txtBatch.Text.Trim(),
                Date = (DateTime)dtpDate.Value,
                SerialNumber = (int)serialNumber.Value,
                Notes = txtNotes.Text.Trim()
            };

        }

        private void UpdateCurrentTemplate()
        {
            var templates = _templateService.GetAllTemplates();
            if (templates != null && templates.Count > 0)
            {
                // 优先选择默认模板
                var defaultTemplate = templates.Find(t => t.IsDefault);
                if (defaultTemplate != null)
                {
                    _currentTemplate = defaultTemplate;
                    cboTemplates.SelectedItem  = defaultTemplate;
                }
                else
                {
                    // 如果没有默认模板，选择第一个模板
                    _currentTemplate = templates[0];
                    cboTemplates.SelectedItem = templates[0];
                }
            }
            else
            {
                _currentTemplate = null;
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                var workOrder = GetWorkOrderFromForm();
                
                // 验证必要字段
                if (string.IsNullOrEmpty(workOrder.Model) || string.IsNullOrEmpty(workOrder.Batch))
                {
                    MessageBox.Show("请输入型号和批次信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (_currentTemplate == null)
                {
                    UpdateCurrentTemplate();
                }

                if (_currentTemplate == null)
                {
                    MessageBox.Show("未找到可用的打印模板", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                // 自动递增序号
                serialNumber.Value = serialNumber.Value + 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打印失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClearInput_Click(object sender, EventArgs e)
        {
            txtModel.Clear();
            txtBatch.Clear();
            dtpDate.Value = DateTime.Now;
            serialNumber.Value = 1;
            txtNotes.Clear();
            _currentTemplate = null;
        }

        private void btnResetSerial_Click(object sender, EventArgs e)
        {
            serialNumber.Value = 1;
        }

        private void btnManageTemplates_Click(object sender, EventArgs e)
        {
            using (var templateForm = new TemplateManagementForm(_templateService))
            {
                if (templateForm.ShowDialog() == DialogResult.OK)
                {
                    LoadTemplateList();
                    UpdateCurrentTemplate();
                }
            }
        }

        private void cboTemplates_SelectedValueChanged(object sender, AntdUI.ObjectNEventArgs e)
        {
            if (cboTemplates.SelectedValue is PrintTemplate template)
            {
                _currentTemplate = template;
            }

        }

        private void txtModel_TextChanged(object sender, EventArgs e)
        {
            // 获取型号输入框的文本
            string modelText = txtModel.Text.Trim();

            // 如果输入为空，长度小于10则不进行匹配
            if (string.IsNullOrEmpty(modelText) && modelText.Length <10)
                return;

            // 截取前3个字符
            string modelPrefix = modelText.Length >= 3 ? modelText.Substring(0, 3) : modelText;

            // 获取所有模板
            var templates = _templateService.GetAllTemplates();

            // 查找匹配的模板
            var matchedTemplate = templates.FirstOrDefault(t =>
                !string.IsNullOrEmpty(t.Model) &&
                t.Model.Equals(modelPrefix, StringComparison.OrdinalIgnoreCase));

            // 如果找到匹配的模板，设置为当前模板，否则显示默认模板
            if (matchedTemplate != null)
            {
                _currentTemplate = matchedTemplate;
                cboTemplates.SelectedItem = matchedTemplate;
            }
        }
    }
}
